package main

import (
	"encoding/json"
	"fmt"
	"gitee.com/leaf-rain-gitee/util/dingding"
	"gitee.com/leaf-rain-gitee/util/log"
	"gitee.com/leaf-rain-gitee/util/panicRecover"
	"gitee.com/leaf-rain-gitee/util/timeUtil"
	"go.uber.org/zap"
	"io/ioutil"
	"net/http"
	"runtime"
	"sync"
	"time"
)

var (
	dingdingUrl         = "https://oapi.dingtalk.com/robot/send?access_token=f482728d0abbd6b9b16e282b199b085eabc5d0a04f2777bbd595672be116fa1e"
	defaultRate float64 = 55
)

func main() {
	var tp = map[string]string{
		"3":  "5min",
		"10": "15min",
		"11": "30min",
		"2":  "1hour",
		"1":  "4hour",
		"4":  "12hour",
		"5":  "24hour",
	}
	_, _ = log.NewLogger(new(log.Options))
	var wg sync.WaitGroup
	for key, value := range tp {
		wg.Add(1)
		go func(key, value string) {
			getEth(key, value)
			defer wg.Done()
			defer panicRecover.RecoverPanic()
		}(key, value)
	}
	wg.Wait()
}

func getEth(ty, te string) {
	url := fmt.Sprintf("https://fapi.bybt.com/api/futures/longShortRate?timeType=%s&symbol=ETH", ty)
	var msg string
	var longRate float64 = 0
	var shortRate float64 = 0
	for {
		reply, err := http.Get(url)
		if err != nil || reply.StatusCode != 200 {
			log.GetLogger().Error("get url failed", zap.Error(err))
			continue
		}
		if reply != nil {
			body, err := ioutil.ReadAll(reply.Body)
			if err != nil {
				log.GetLogger().Error("ioutil ReadAll failed", zap.Error(err))
				continue
			}
			var resp response
			err = json.Unmarshal(body, &resp)
			if err != nil {
				log.GetLogger().Error("json Unmarshal failed", zap.Error(err))
				continue
			}
			if len(resp.Data) > 0 {
				log.GetLogger().Info(fmt.Sprintf("%s获取成功", te), zap.Any("看涨为：", resp.Data[0].LongRate), zap.Any("看空为：", resp.Data[0].ShortRate))
			}
			if len(resp.Data) == 0 {
				continue
			}
			switch {
			case resp.Data[0].LongRate > defaultRate:
				if ty == "3" {
					if resp.Data[0].LongRate < (defaultRate + 10) {
						break
					}
				}
				if resp.Data[0].LongRate > (longRate + 3) {
					longRate = resp.Data[0].LongRate
					msg = fmt.Sprintf("干饭了, 在%s内eth看涨超过 %f%%，%s \n", te, resp.Data[0].LongRate, timeUtil.FormatTime(time.Now()))
					dingding.SendTextToDingding(dingdingUrl, msg, nil, nil, false)
				}
			case resp.Data[0].ShortRate > defaultRate:
				if ty == "3" {
					if resp.Data[0].LongRate < (defaultRate + 10) {
						break
					}
				}
				if resp.Data[0].ShortRate > (shortRate + 3) {
					shortRate = resp.Data[0].ShortRate
					msg = fmt.Sprintf("干饭了, 在%s内eth看空超过 %f%%， %s \n", te, resp.Data[0].ShortRate, timeUtil.FormatTime(time.Now()))
					dingding.SendTextToDingding(dingdingUrl, msg, nil, nil, false)
				}
			default:
				longRate = resp.Data[0].LongRate
				shortRate = resp.Data[0].ShortRate
				msg = ""
			}
		}
		time.Sleep(time.Second * 30)
		runtime.Gosched()
	}
}

type response struct {
	Code string `json:"code"`
	Msg  string `json:"msg"`
	Data []struct {
		Symbol         string  `json:"symbol"`
		TurnoverNumber int     `json:"turnoverNumber"`
		LongRate       float64 `json:"longRate"`
		LongVolUsd     float64 `json:"longVolUsd"`
		ShortRate      float64 `json:"shortRate"`
		ShortVolUsd    float64 `json:"shortVolUsd"`
		SymbolLogo     string  `json:"symbolLogo"`
		TotalVolUsd    float64 `json:"totalVolUsd"`
		List           []struct {
			ExchangeName       string  `json:"exchangeName"`
			OriginalSymbol     string  `json:"originalSymbol"`
			Symbol             string  `json:"symbol"`
			Price              float64 `json:"price"`
			Type               int     `json:"type"`
			UpdateTime         int64   `json:"updateTime"`
			QuoteCurrency      string  `json:"quoteCurrency"`
			TurnoverNumber     int     `json:"turnoverNumber"`
			LongRate           float64 `json:"longRate"`
			LongVolUsd         float64 `json:"longVolUsd"`
			ShortRate          float64 `json:"shortRate"`
			ShortVolUsd        float64 `json:"shortVolUsd"`
			ExchangeLogo       string  `json:"exchangeLogo"`
			SymbolLogo         string  `json:"symbolLogo"`
			TotalVolUsd        float64 `json:"totalVolUsd"`
			HighPrice          float64 `json:"highPrice"`
			LowPrice           float64 `json:"lowPrice"`
			OpenPrice          float64 `json:"openPrice"`
			PriceChange        float64 `json:"priceChange"`
			PriceChangePercent float64 `json:"priceChangePercent"`
			BuyTurnoverNumber  int     `json:"buyTurnoverNumber"`
			SellTurnoverNumber int     `json:"sellTurnoverNumber"`
		} `json:"list"`
	} `json:"data"`
	Success bool `json:"success"`
}
